package com.example.appkcsj.DAO;

import com.example.appkcsj.dbutils.DB;
import com.example.appkcsj.entity.Family;
import ohos.agp.render.render3d.Entity;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmObject;
import ohos.data.orm.OrmPredicates;

import java.util.List;

public class FamilyDaoImpl implements FamilyDao{

    private OrmContext ormContext;
    public FamilyDaoImpl(Context context) {
        DatabaseHelper helper = new DatabaseHelper(context);
        ormContext = helper.getOrmContext("Family","Family.db", DB.class);
    }


    @Override
    public boolean insert(Family family) {
        ormContext.insert(family);
        return ormContext.flush();
    }

    @Override
    public boolean deleteByName(String name1) {
        OrmPredicates predicates = ormContext.where(Family.class).equalTo("name1",name1);
        List<OrmObject> entitys = ormContext.query(predicates);
        ormContext.delete(entitys.get(0));
        return ormContext.flush();
    }

    @Override
    public boolean updata(Family family) {
        OrmPredicates predicates=ormContext.where(Family.class).equalTo("name1",family.getName1());
        List<Family> families = ormContext.query(predicates);
        Family updateFamily = families.get(0);
        updateFamily.setName1(family.getName1());
        updateFamily.setName(family.getName());
        updateFamily.setPhone(family.getPhone());
        updateFamily.setAge(family.getAge());
        updateFamily.setAddress(family.getAddress());
        updateFamily.setBirth(family.getBirth());
        ormContext.update(updateFamily);
        return ormContext.flush();
    }

    @Override
    public Family queryByName(String name1) {
        OrmPredicates predicates = ormContext.where(Family.class).equalTo("name1",name1);
        List<Family> entitys = ormContext.query(predicates);
        if(entitys.size() == 0){
            return null;
        }else {
            return entitys.get(0);
        }
    }
}
